<template>
  <div class="product-management">
    <h1>产品管理</h1>
    
    <!-- 搜索和操作区 -->
    <el-card class="search-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入产品名称或描述搜索"
            prefix-icon="el-icon-search"
            clearable
          ></el-input>
        </el-col>
        <el-col :span="8">
          <el-select v-model="searchForm.category" placeholder="选择分类" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option v-for="cat in categories" :key="cat" :label="cat" :value="cat"></el-option>
          </el-select>
        </el-col>
        <el-col :span="8" class="text-right">
          <el-button type="primary" @click="handleCreateProduct">
            <i class="el-icon-plus"></i> 新增产品
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 产品列表 -->
    <el-card class="data-card">
      <el-table :data="filteredProducts" style="width: 100%">
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column label="产品图片" width="100">
          <template #default="scope">
            <el-avatar :size="40" :src="scope.row.imageUrl || ''">
              {{ scope.row.name.charAt(0) }}
            </el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="产品名称"></el-table-column>
        <el-table-column prop="category" label="分类" width="120"></el-table-column>
        <el-table-column prop="price" label="价格" width="100">
          <template #default="scope">
            ¥{{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100">
          <template #default="scope">
            <span :class="{ 'low-stock': scope.row.stock < 10 }">
              {{ scope.row.stock }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="tags" label="标签" width="150">
          <template #default="scope">
            <el-tag size="small" v-for="tag in scope.row.tags" :key="tag">
              {{ tag }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEditProduct(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDeleteProduct(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredProducts.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 产品编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑产品' : '新增产品'"
      width="600px"
    >
      <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="100px">
        <el-form-item label="产品名称" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入产品名称"></el-input>
        </el-form-item>
        <el-form-item label="产品分类" prop="category">
          <el-select v-model="editForm.category" placeholder="请选择分类">
            <el-option v-for="cat in categories" :key="cat" :label="cat" :value="cat"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品价格" prop="price">
          <el-input-number
            v-model="editForm.price"
            :min="0"
            :step="0.01"
            style="width: 100%"
            placeholder="请输入价格"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="库存数量" prop="stock">
          <el-input-number
            v-model="editForm.stock"
            :min="0"
            style="width: 100%"
            placeholder="请输入库存"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="产品标签" prop="tags">
          <el-select
            v-model="editForm.tags"
            multiple
            placeholder="请选择标签"
            collapse-tags
          >
            <el-option v-for="tag in allTags" :key="tag" :label="tag" :value="tag"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品描述" prop="description">
          <el-input
            v-model="editForm.description"
            type="textarea"
            rows="4"
            placeholder="请输入产品描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveProduct">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { api } from '../utils/axios'
const { get, post, put, delete: del } = api
import { ElMessage, ElMessageBox } from 'element-plus'
import { products } from '../utils/mockData.js'

// 产品数据
const productList = ref([])

// 搜索表单
const searchForm = reactive({
  keyword: '',
  category: ''
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10
})

// 对话框配置
const dialogVisible = ref(false)
const isEditMode = ref(false)
const editFormRef = ref()
const editForm = reactive({
  id: '',
  name: '',
  category: '',
  price: 0,
  stock: 0,
  tags: [],
  description: ''
})

// 分类和标签数据
const categories = ['电子产品', '家居用品', '服装鞋帽', '食品饮料', '运动健身']
const allTags = ['热销', '新品', '限时优惠', '推荐', '爆款', '库存紧张']

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入产品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '产品名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择产品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入产品价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格必须大于等于0', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存必须大于等于0', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '产品描述不能超过200个字符', trigger: 'blur' }
  ]
}

// 过滤后的产品数据
const filteredProducts = computed(() => {
  let result = [...productList.value]
  
  // 按关键词过滤
  if (searchForm.keyword) {
    const keyword = searchForm.keyword.toLowerCase()
    result = result.filter(product => 
      product.name.toLowerCase().includes(keyword) || 
      product.description.toLowerCase().includes(keyword)
    )
  }
  
  // 按分类过滤
  if (searchForm.category) {
    result = result.filter(product => product.category === searchForm.category)
  }
  
  return result
})

// 加载产品数据
const loadProducts = () => {
  productList.value = JSON.parse(JSON.stringify(products))
}

// 创建产品
const handleCreateProduct = () => {
  isEditMode.value = false
  Object.assign(editForm, {
    id: '',
    name: '',
    category: '',
    price: 0,
    stock: 0,
    tags: [],
    description: ''
  })
  dialogVisible.value = true
}

// 编辑产品
const handleEditProduct = (product) => {
  isEditMode.value = true
  Object.assign(editForm, {
    id: product.id,
    name: product.name,
    category: product.category,
    price: product.price,
    stock: product.stock,
    tags: [...product.tags],
    description: product.description || ''
  })
  dialogVisible.value = true
}

// 保存产品
const handleSaveProduct = async () => {
  await editFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      if (isEditMode.value) {
        // 编辑产品
        const index = productList.value.findIndex(p => p.id === editForm.id)
        if (index !== -1) {
          productList.value[index] = {
            ...productList.value[index],
            name: editForm.name,
            category: editForm.category,
            price: editForm.price,
            stock: editForm.stock,
            tags: editForm.tags,
            description: editForm.description
          }
          ElMessage.success('产品编辑成功')
        }
      } else {
        // 创建新产品
        const newProduct = {
          id: Date.now(),
          name: editForm.name,
          category: editForm.category,
          price: editForm.price,
          stock: editForm.stock,
          tags: editForm.tags,
          description: editForm.description,
          imageUrl: '' // 可以在这里添加图片上传功能
        }
        productList.value.unshift(newProduct)
        ElMessage.success('产品创建成功')
      }
      dialogVisible.value = false
    } catch (error) {
      ElMessage.error('操作失败，请重试')
    }
  })
}

// 删除产品
const handleDeleteProduct = (productId) => {
  ElMessageBox.confirm(
    '确定要删除这个产品吗？',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = productList.value.findIndex(p => p.id === productId)
    if (index !== -1) {
      productList.value.splice(index, 1)
      ElMessage.success('产品删除成功')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.pageSize = size
}

const handleCurrentChange = (current) => {
  pagination.currentPage = current
}

// 组件挂载时加载数据
onMounted(() => {
  loadProducts()
})
</script>

<style scoped>
.product-management {
  padding: 20px;
  height: 100%;
}

.search-card {
  margin-bottom: 20px;
}

.data-card {
  height: calc(100% - 120px);
  display: flex;
  flex-direction: column;
}

.el-table {
  flex: 1;
  overflow: auto;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.low-stock {
  color: #f56c6c;
  font-weight: bold;
}

.text-right {
  text-align: right;
}
</style>